package com.java.reggie.Controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.java.reggie.common.R;
import com.java.reggie.entity.User;
import com.java.reggie.service.UserService;
import com.java.reggie.utils.SendMailUtil;
import com.java.reggie.utils.ValidateCodeUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Autowired
    private UserService userService;
    @Autowired
    private SendMailUtil sendMailUtil;

    /**
     * 发送邮箱验证码
     * @param user
     * @return
     */
    @PostMapping("/sendMsg")
    public R<String> sendMSg(@RequestBody User user, HttpSession session){
        //获取邮箱
        String email = user.getEmail();
        if(StringUtils.isNotEmpty(email)){
            //生成验证码
            String loginCode = ValidateCodeUtils.generateValidateCode(4).toString();
            //发送邮件
            //sendMailUtil.sendMail(email,"瑞吉外卖验证码",loginCode);
            //将生成的验证码保存进Session
            session.setAttribute(email,loginCode);
            log.info("------------------------验证码：{}",loginCode);
            return R.success("手机验证码发送成功");
        }

        return R.success("手机验证码发送失败");
    }

    /**
     * 移动端用户登录
     * @param
     * @param session
     * @return
     */
    @PostMapping("/login")
    public R<User> login(@RequestBody Map map, HttpSession session){
        log.info(map.toString());
        //获取邮箱
        String email = map.get("email").toString();
        //获取验证码
        String code = map.get("code").toString();
        //从session中获取保存的验证码
        Object codeInSession = session.getAttribute(email);
        //对比
        if(codeInSession != null && codeInSession.equals(code)){
            //判断是否为新用户，如果是自动注册
            LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(User::getEmail,email);
            User user = userService.getOne(queryWrapper);
            if(user == null){
                user = new User();
                user.setEmail(email);
                user.setStatus(1);
                userService.save(user);
            }
            session.setAttribute("user",user.getId());
            return R.success(user);
        }
        return R.error("登录失败");
    }



}
